
def greedy_max_path(grid):
    m, n = len(grid), len(grid[0])
    path = [(0,0)]
    x, y = 0, 0
    visited = [[False]*n for _ in range(m)]
    visited[0][0] = True
    scores = [grid[0][0]]
    
    while (x, y) != (m-1, n-1):
        best_val = -float('inf')
        next_pos = None
        for dx, dy in [(0,1),(1,0),(0,-1),(-1,0)]:
            nx, ny = x+dx, y+dy
            if 0<=nx<m and 0<=ny<n and not visited[nx][ny]:
                if grid[nx][ny] > best_val:
                    best_val = grid[nx][ny]
                    next_pos = (nx, ny)
                    scores.append(grid[nx][ny])
        if next_pos is None:
            # print("Stuck, no path to end")
            break
        x, y = next_pos
        visited[x][y] = True
        path.append((x,y))
    
    return min(scores)


if __name__ == "__main__":
    # grid = [[5, 4, 5]]
    grid = [[0]]
    # grid = [[5, 4, 5], [1, 2, 6], [7, 4, 6]]

    print(greedy_max_path(grid))